package com.dshore.messagecenter.service.topicQueue.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dshore.messagecenter.dao.topicqueue.TopicAccessDao;
import com.dshore.messagecenter.dao.topicqueue.TopicQueueDao;
import com.dshore.messagecenter.dao.topicqueue.TopicSendDao;
import com.dshore.messagecenter.dao.warning.ExceptionMessageDao;
import com.dshore.messagecenter.model.basedata.MdApp;
import com.dshore.messagecenter.model.system.ResponseResult;
import com.dshore.messagecenter.model.system.SysDict;
import com.dshore.messagecenter.model.topicqueue.MdTopic;
import com.dshore.messagecenter.model.topicqueue.MdTopicAccess;
import com.dshore.messagecenter.model.topicqueue.MdTopicSend;
import com.dshore.messagecenter.service.topicQueue.TopicQueueService;
import com.dshore.messagecenter.util.Page;
import com.dshore.messagecenter.util.RabbitUtil;
import com.dshore.messagecenter.util.UUIDUtil;


@Service
public class TopicQueueServiceImpl implements TopicQueueService {
	@Value("${spring.rabbitmq.virtual-host}")
	private String vhostName;
	//发送队列后缀-服务接入
	@Value("${access_url}")
	private String accessUrl;
	
	@Autowired
	private RabbitUtil rabbitUtil;
	
	private static final Logger logger = LoggerFactory.getLogger(TopicQueueServiceImpl.class);
	
	@Autowired
	private TopicQueueDao topicQueueDao;
	@Autowired
	private TopicAccessDao topicAccessDao;
	@Autowired
	private TopicSendDao topicSendDao;
	@Autowired
	private ExceptionMessageDao exceptionMessageDao;
	/**
	 * 查询所有主题队列
	 * @return
	 */
	@Override
	public List<MdTopic> queryAllTopicQueue() {
		List<MdTopic> list = topicQueueDao.queryAllQueueTopic();
		return list;
	}
	
	@Override
	public List<Map<String, Object>> getAccessType() {
		return topicQueueDao.getAccessType();
	}

	@Override
	public Page<Map<String, Object>> queryListAll(MdTopic queue, String checkAppId) {
//		System.out.println("---------初始化页面-----------");
		//总记录数
		long total= topicQueueDao.queryCountByPrama(queue,checkAppId);
//		System.out.println("消息队列总记录数: " +total);
//		System.out.println("消息队列当前页从第几条开始查询: " + queue.getOffset());
		// 防止跳转到其他页时带参查询bug(总记录小于每页显示个数或小于offset每页的开始下标)
		if(total < queue.getOffset()) {
			// 将开始查询的条数设置为0
			queue.setOffset(0);
		}
	    //模糊查询
		List<Map<String, Object>> list = topicQueueDao.queryListByPrama(queue,checkAppId);
//		System.out.println("第一条数据: " + list.get(0));
//		System.out.println("第一条数据发布状态: " + list.get(0).getStatus());
//		System.out.println("查询所有消息队列个数: " + list.size());
		//重构对象,方便扩展
//		List<Map<String, Object>> mapList = new ArrayList<Map<String,Object>>();
		/*for(MdTopic topicQueue : list) {
			Map<String, Object> map = BeanToMap.ConvertObjToMap(topicQueue);
			
			String statusVal =	topicQueueDao.queryStatus(topicQueue.getStatus());
//			System.out.println("发布状态: " + statusVal);
			String accessTypeVal =	topicQueueDao.queryAccessType(topicQueue.getAccessType());
//			System.out.println("接入方式: " + accessTypeVal);
//			String originApp = topicQueueDao.queryOriginApp(queue.getOriginAppId());
			// todo 源应用ID、消息模板ID、目标应用IDS
//			System.out.println("------------");
			String topicQueueNo = topicQueue.getTopicQueueNo();
//			System.out.println("主题队列编码: " + topicQueueNo);
			// 查询模板
			MdTopic  mdTopic = topicQueueDao.queryMsgTemplate(topicQueueNo);
					String templateName = "";
			if(templateNameList.size() > 0) {
				templateName = templateNameList.get(0);
			}
//			System.out.println("模板名称templateName: " + templateName);
			if(mdTopic.getTemplateName()!=null) {
				map.put("templateName", mdTopic.getTemplateName());
			}else {
				map.put("templateName", null);
			}
			
			//查询源应用(查不到显示[])
			List<String> oriApps = topicQueueDao.queryOriAppName(topicQueueNo);
//			System.out.println("oriApps: " + oriApps);
			String oriAppName = "";
			if(oriApps.size() > 0) {
				oriAppName = oriApps.get(0);
			}
//			System.out.println("源应用名称： " + oriAppName);
			//查询目标应用个数(即发送个数)
			Integer tAppNum = topicQueueDao.queryTAppNum(topicQueueNo);
//			System.out.println("目标应用个数: " + tAppNum);
			
			String releaseStatus = topicQueue.getStatus();
			map.put("releaseStatus", releaseStatus);
			map.put("oriAppName", oriAppName);
			map.put("tAppNum", tAppNum);
			map.put("accessTypeVal", accessTypeVal);
			map.put("statusVal", statusVal);
			mapList.add(map);
		}*/
		Page<Map<String, Object>> page = new Page<Map<String, Object>>(queue.getLimit(),total,queue.getOffset(),list);
		return page;
	}

	@Override
	public Integer insertObj(MdTopic queue) {
		return 0;
	}
	/**
	 * 根据id查询队列信息
	 */
	@Override
	public MdTopic queryById(String id) {
		MdTopic topic = topicQueueDao.queryById(id);
		return topic;
	}


	/**
	 * 逻辑删除
	 */
	@Override
	public ResponseResult<Void> deleteByIds(String[] ids) {
		ResponseResult<Void>responseResult=new ResponseResult<>();
		
		//查询队列的topicQueueNo
		List<String> queueSigns = topicQueueDao.queryTopicQueueNoById(ids);
		//list转为数组
		String[] qSigns =  queueSigns.toArray(new String[queueSigns.size()]);
		//System.out.println("数组qSigns: " + Arrays.toString(qSigns));

		int result1 = 0;
		int result2 = 0;
		int result4=0;
		//遍历删除接入表
		result1 = topicAccessDao.deleteAccessByQueueSigns(qSigns);
		//删除发送表
		result2 = topicSendDao.deleteSendByQueueSigns(qSigns);
		
		//删除主题队列
		int result3 = topicQueueDao.deleteByIds(ids);
		//System.out.println("删除队列: " + result3 +", 批量删除Access: " + result1 + ", 删除Send: " + result2);
		//删除异常信息
		result4=exceptionMessageDao.deleteByTopicDeleted(qSigns);
		if(result1 != 0 && result2 != 0 && result3 != 0) {
//			System.out.println("删除队列、接入、发送表成功！");
			responseResult.setState(200);
			responseResult.setMessage("删除成功");
			return responseResult;
		}
		responseResult.setState(400);
		responseResult.setMessage("删除操作异常!");
		return responseResult;
	}
	
	/*public static void main(String[] args) {
		List<String> queueSigns = new ArrayList<>();
		queueSigns.add("a");
		queueSigns.add("ac");
		System.out.println("queueSigns： " + queueSigns);
		String[] qSigns =  queueSigns.toArray(new String[queueSigns.size()]);
		System.out.println("数组qSigns: " + Arrays.toString(qSigns));
		for(String sign : qSigns) {
			System.out.println("sign: " + sign);
		}
		
		String idArr = "a,ds,as";
		String[] ids = idArr.split("\\,");
		System.out.println("数组ids: " + Arrays.toString(ids));
		
	}*/
	
	/**
	 * 发布/ 撤回
	 */
	@Override
	public int releaseOrRecall(String id, int status) {
		return topicQueueDao.releaseOrRecall(id, status);
	}

	
	
	
	
	/**
	 * 根据接入获取源应用
	 */
	@Override
	public MdApp queryAppByAccess(String topicQueueNo) {
		//接入
		List<MdTopicAccess> list = topicAccessDao.queryByTopicSign(topicQueueNo);
//		logger.info("接入集合(" + list.size() + "个)");
		
		String[] queueKey = {};
		//Map<String, Object> map = new HashMap<String, Object>();
		MdApp mdApp=new MdApp();
		if(list!=null && list.size() > 0) {
			//只取第一个对象
			MdTopicAccess access = list.get(0);
			if(access != null) {
				String accessAppId = access.getAccessAppid();
				if(StringUtils.isNotBlank(accessAppId)) {
					//源应用(根据id查询一个)
					
					MdApp app = topicAccessDao.queryOriApp(accessAppId);
					//map = BeanToMap.ConvertObjToMap(app);
					app.setId(accessAppId);
					queueKey = app.getQueueKey().split(",");
					/*map.put("user", queueKey[0]);//源应用用户名
					map.put("password", queueKey[1]);//源应用密码
					map.put("AccessUrl", access.getAccessUrl());//源应用密码*/
					app.setAccessUrl(access.getAccessAppid());
					app.setAccessUrl(access.getAccessUrl());
					mdApp=app;
					}
			}
		}
		return mdApp;
	}

	/**
	 * 根据topicQueueNo获取目标应用(多个)
	 */
	@Override
	public List<MdApp> queryAppsBySend(String topicQueueNo) {
//		logger.info("发送目标参数: " + topicQueueNo);
		//发送id集合
		List<Map<String, Object>> targetList = topicSendDao.queryByTopicSign(topicQueueNo);
		logger.info("发送目标集合(" + targetList.size() + "个) ");
		//目标应用(多个)
		/*String[] queueKey = {};*/
		//Map<String, Object> map = new HashMap<String, Object>();
		List<MdApp> apps = new ArrayList<>();
		if(targetList.size() > 0) {
			//遍历发送目标集合获取每个目标appId
			for(Map<String, Object> target : targetList) {
					String targetId = (String)target.get("TARGET_APPID");
					String queueName = (String)target.get("QUEUE_NAME");
					//System.out.println("获取每个目标appId: " + targetId);
					//获取每个目标app
					MdApp app = topicSendDao.queryTargetApp(targetId);
					//map = BeanToMap.ConvertObjToMap(app);
					//map.put("queueName", queueName);
					app.setQueueName(queueName);
					app.setId(targetId);
				/*	if(StringUtils.isNotBlank(app.getQueueKey())) {
						queueKey = app.getQueueKey().split(",");
						//map.put("user", queueKey[0]);//目标应用用户名
						//map.put("password", queueKey[1]);//目标应用密码
					}*/
					apps.add(app);
			}
		}
//		System.out.println("目标apps: " + apps);
		return apps;
	}
	/**
	 * 主题队列撤回流程
	 */
	@Override
	public int queueWidthdraw(String topicQueueNo,String vhostName, String id, int status) {
		//源应用
		List<String> oriQueueKeys = topicQueueDao.queryOriAppUser(topicQueueNo);
		String oriQueueKey = "";
		//用户名key
		String[] queueKey = {};
		
		//源应用用户名
		String oriUserName = "";
		if(oriQueueKeys.size() > 0) {
			oriQueueKey = oriQueueKeys.get(0);
			queueKey = oriQueueKey.split(",");
			oriUserName = queueKey[0];//源应用应用用户名
		}
//		System.out.println("源应用用户名: " + oriUserName + ", 虚拟主机名称： " + vhostName);
		//1.为源应用清除写无权限
//		rabbitUtil.clearPermission(oriUserName, vhostName);
		
		
		List<MdApp> tApps = topicQueueDao.querytApp(topicQueueNo);
		//目标应用用户名
		String tarUserName = "";
//		System.out.println("用户名集合个数: " + tQueueKeys.size());
		if(tApps.size() > 0) {
			for(MdApp tApp : tApps) {
				if(StringUtils.isNotBlank(tApp.getQueueKey())) {
					queueKey=tApp.getQueueKey().split(",");
					tarUserName = queueKey[0];//目标应用应用用户名
					//2.循环为目应用标清除写权限
//					System.out.println("目标应用用户名: " + tarUserName);
//					rabbitUtil.clearPermission(tarUserName, vhostName);
				}
			}
		}
		//2.更新数据库
		int update = releaseOrRecall(id, status);
		return update;
	}
	
	/**
	 * 主题队列发布流程
	 */
	@Override
	public int queueRelease(String topicQueueNo, String vhostName, String id, int status) {
		//源应用(根据消息队列编码查询)
		List<MdApp> oriApps = topicQueueDao.queryOriAppBySign(topicQueueNo);
		String oriQueueKey = "";
		//用户名key
		String[] queueKey = {};
		
		//源应用用户名
		String oriUserName = "";
		MdApp oriApp = null;
		
		//1.校验能否发布
		if(oriApps.size() > 0) {
			oriApp = oriApps.get(0);
			if(oriApp.getStatus().equals("1001")) {//2 提示启用源应用
				return 2;
			}
			//userName
			oriQueueKey = oriApp.getQueueKey();
			if(StringUtils.isNotBlank(oriQueueKey)) {
				queueKey = oriQueueKey.split(",");
				oriUserName = queueKey[0];//源应用应用用户名
			}
		}
		//判断源应用的状态，如果没有该应用，提示完善节点
		else if(oriApps.size() == 0) {// 3提示配置源应用
			return 3;
		}
//		System.out.println("源应用用户名: " + oriUserName + ", 虚拟主机名称： " + vhostName);
		
		
		List<MdApp> tApps = topicQueueDao.querytApp(topicQueueNo);
		//目标应用用户名
		String tarUserName = "";
		List<String> tarList = new ArrayList<>();
//		System.out.println("用户名集合个数: " + tQueueKeys.size());
		if(tApps.size() > 0) {
			for(MdApp tApp : tApps) {
//				System.out.println("目标应用信息: " + tApp);
				String tQueueKey = tApp.getQueueKey();
				//判断应用的启用状态，没启用提示启动(1001停用，1002启用)
				if(tApp.getStatus().equals("1001")) {//4 提示启用目标应用
					return 4;
				}else {
					
					if(StringUtils.isNotBlank(tQueueKey)) {
						queueKey = tQueueKey.split(",");
						tarUserName = queueKey[0];//目标应用应用用户名
						tarList.add(tarUserName);
					}
				}
			}
		}
		//判断目标应用的状态，如果没有该应用，提示完善目标应用节点
		else if(tApps.size() == 0)  {
			return 4;
		}
		if(StringUtils.isNotBlank(oriUserName) &&  tarList.size() > 0) {
			
			//2.更新数据库
			int update = releaseOrRecall(id, status);
			
			//3.为源应用分配写权限(1)
//			System.out.println("给源应用分配写权限(1): " + oriUserName +  ", 虚拟主机名称： " + vhostName);
//			rabbitUtil.setPermission(oriUserName, vhostName,1);
			//4.循环为目应用标分配读权限(0)
			int i =0;
			for(String userName : tarList) {
//				System.out.println("第" + i + "次给目标应用userName分配读权限(0): " + userName);
				try {
//					rabbitUtil.setPermission(userName, vhostName,0);
				} catch (Exception e) {
					e.printStackTrace();
				}
				i++;
			}
			return update;
		}
		
		//异常返回0
		return 0;
	}
	

	/**
	 * 保存应用
	 */
	@Override
	public ResponseResult<Void> saveApps(Map<String, Object> map, String topicQueueName, HttpSession session, 
			String key, String status) {
		ResponseResult<Void> responseResult=new ResponseResult<>();
		try{
					/**主题队列主键有值,修改*/
					if(map.containsKey("tId")) {
					//根据id主键查询主题队列所有信息(从而取queueSign)
					MdTopic topic = topicQueueDao.queryById(map.get("tId").toString());
					
					//心弦的目标应用id集合
					List<Map<String, String>> targetList = (List<Map<String, String>>) map.get("targetList");
					if(status.equals("1302")) {
						
						//主题队列主键有值，为修改操作(修改时编码不变，access和queue表只更新，send表查出数据删除后重新新增)
						String tId = map.get("tId").toString();
						//1.更新topicQueueName
						int result = topicQueueDao.updateQueueName(tId,topicQueueName);
		//				System.out.println("更新主题队列名称结果: " + result);
						// 发布状态下更新目标应用
						if (topic != null) {
							if (rabbitUtil.updateTargetApp(topic.getTopicQueueNo(), targetList)) {
								responseResult.setState(200);
								responseResult.setMessage("ok");
								return responseResult;
							}
						}
					}
					else {
						
						
						//主题队列主键有值，为修改操作(修改时编码不变，access和queue表只更新，send表查出数据删除后重新新增)
						String tId = map.get("tId").toString();
						//1.更新topicQueueName
						int result = topicQueueDao.updateQueueName(tId,topicQueueName);
		//				System.out.println("更新主题队列名称结果: " + result);
						
						int oriResult = 0;
						Map<String, String> originInfo = (Map<String, String>) map.get("origin");
						if(originInfo != null) {
							String originId = originInfo.get("originId");
		//					System.out.println("源应用id: " + originId);
							//2.更新access表源应用
							oriResult = topicQueueDao.updateOriApp(tId,originId);
		//					System.out.println("更新源应用结果: " + oriResult);
						}
						
						//3.新增目标应用
						Integer tarResult = 0;
						if(topic != null) {
							String queueSign = topic.getTopicQueueNo();
							//遍历逻辑删除目标应用
							int result1 = topicQueueDao.deleteTApps(queueSign);
							System.out.println("删除原来队列的目标应用 " + result1 + " 个");
							
							
							//2.新增目标应用
							int seq=0;
							if(targetList.size() > 0) {
								for(Map<String, String> tApp : targetList) {
									seq++;
									String targetId = (String) tApp.get("targetId");
									tarResult = topicSendDao.saveTApp(UUIDUtil.getUUId(),0,topic.getTopicQueueNo(),targetId,seq);
								}
							}
		//					System.out.println("修改后保存队列名结果: " + result + ", 源应用结果: " + oriResult + ", 目标应用结果: " + tarResult);
							
						}
						if(result ==1 && (oriResult == 1 || oriResult == 0) && tarResult == 1 ) {
							//保存成功后删除session
							session.removeAttribute(key);
							responseResult.setState(200);
							responseResult.setMessage("ok");
							return responseResult;
						}
					}
				}
				/**主题队列主键没值,新增*/
				else {
					//主题队列主键没值，为新增操作
		
					Map<String, String> origin = (Map<String, String>) map.get("origin");
					//查询递增的最后一条主题队列编码
					List<String> topicQueueNos = topicQueueDao.queryAllQueueSigns();
					
		
			        //确定主题队列编码topicQueueNo
			        String topicQueueNo = new StringBuffer("TOPIC").append(String.format("%06d", 1)).toString();//一条数据没有则默认 TOPIC000001 
		//	        System.out.println("初始化的编码topicQueueNo: " + topicQueueNo);
					//截取TOPIC前5位数，取后面数字递增
			        if(topicQueueNos.size() > 0) {
			        	topicQueueNo = topicQueueNos.get(0).substring(5);
		//	            System.out.println("查询出来的数据库编码: " + topicQueueNo);
			    		if( StringUtils.isNotBlank(topicQueueNo)) {
			    			//递增
			                int queueNum = Integer.parseInt(topicQueueNo) + 1;
			                //递增后自动补6位
			                topicQueueNo = new StringBuffer("TOPIC").append(String.format("%06d", queueNum)).toString();
			    		}
			        }
		//	        System.out.println("自增后主题队列编码: " + topicQueueNo);
		//			
		
			        int delFlag = 0;
					//1)存入源应用
					String originId = (String)origin.get("originId");
					Integer oriResult = topicAccessDao.saveOriApp(UUIDUtil.getUUId(),delFlag,topicQueueNo,originId);
		//			System.out.println("保存源应用结果: " + oriResult);
					
					
					//2)遍历存入目标应用(SEND_TYPE 不用传，属于服务接入的推送和拉取)
					List<Map<String, String>> targetList = (List<Map<String, String>>) map.get("targetList");
					Integer tarResult = 0;
					int seq=0;
					if(targetList.size() > 0) {
						for(Map<String, String> tApp : targetList) {
							seq++;
							String targetId = (String) tApp.get("targetId");
							tarResult = topicSendDao.saveTApp(UUIDUtil.getUUId(),delFlag,topicQueueNo,targetId,seq);
						}
					}
		//			System.out.println("保存目标应用结果: " + tarResult);
					
		
					//3)保存消息队列应用
					int tAppNum = targetList.size();	//目标应用个数
					//截取uuid前五位
		//			String uuid = UUIDUtil.getUUId().substring(0,5);
		//	        String vhostName = "vhost-" + uuid;	//虚拟主机名称
		//	        String queueName = "queue-" + uuid;	//队列名称
			        String accessType = "1402";//接入方式(队列)
			        String statuses = "1301";//1301 默认未发布
			        //保存队列结果
					Integer queueResult = topicQueueDao.saveQueue(UUIDUtil.getUUId(),topicQueueName,topicQueueNo,
														accessType,delFlag,statuses,tAppNum);
		//			System.out.println("保存队列结果: " + queueResult);
					
					//三个都成功说明保存成功
					if(oriResult == 1 && tarResult == 1 && queueResult ==1) {
		//				System.out.println("更新主题队列名称、保存源应用、目标应用、保存队列成功！");
						//保存后创建队列和用户
		//				rabbitUtil.createVhost(vhostName);
		//				rabbitUtil.createQueue(vhostName, queueName);
						//保存成功后删除session
						session.removeAttribute(key);
						responseResult.setState(200);
						responseResult.setMessage("ok");
						return responseResult;
					}
				}
				
				responseResult.setState(400);
				responseResult.setMessage("保存失败!");
				return responseResult;
		}catch(Exception e) {
			e.printStackTrace();
			responseResult.setState(400);
			responseResult.setMessage("保存失败!");
			return responseResult;
		}
	}
	/**
	 * 查询发布方式
	 */
	@Override
	public List<SysDict> selectBySendType() {
		return topicSendDao.selectBySendType();
	}
	
	
	
	
	
	
	
	
	
	
	//服务接入
	@SuppressWarnings("unchecked")
	@Override
	public Object saveService(Map<String, Object> map) {
			try {
				//查询递增的最后一条主题队列编码
				List<String> topicQueueNos = topicQueueDao.queryAllQueueSigns();
		        //确定主题队列编码topicQueueNo
		        String topicQueueNo = new StringBuffer("TOPIC").append(String.format("%06d", 1)).toString();//一条数据没有则默认 TOPIC000001 
//		        System.out.println("初始化的编码topicQueueNo: " + topicQueueNo);
				//截取TOPIC前5位数，取后面数字递增
		        if(topicQueueNos.size() > 0) {
		        	topicQueueNo = topicQueueNos.get(0).substring(5);
//		            System.out.println("查询出来的数据库编码: " + topicQueueNo);
		    		if( StringUtils.isNotBlank(topicQueueNo)) {
		    			//递增
		                int queueNum = Integer.parseInt(topicQueueNo) + 1;
		                //递增后自动补6位
		                topicQueueNo = new StringBuffer("TOPIC").append(String.format("%06d", queueNum)).toString();
		    		}
		        }
//		        System.out.println("自增后主题队列编码: " + topicQueueNo);
				//源应用
				Map<String,String>origin=(Map<String,String>)map.get("origin");
				//模板
				Map<String,String>template=(Map<String,String>)map.get("template");
//				System.out.println("模板template="+template);
				//队列名称
				String ServiceName=(String)map.get("ServiceName");
				//发送方式和目标应用
				List<Map<String,String>>targetList=(List<Map<String,String>>)map.get("targetList");
				/*String queueName="queue-"+UUIDUtil.getUUId().substring(0,5);*/
//				String queuesuffix=queueName+queueSuffix;
				//主题信息表
				MdTopic mdTopic=new MdTopic();
				mdTopic.setId(UUIDUtil.getUUId());
				mdTopic.setAccessType("1401");
				mdTopic.setTargetAppNum(String.valueOf(targetList.size()));
				mdTopic.setTopicQueueNo(topicQueueNo);
				mdTopic.setDelFlag(0);
				mdTopic.setVhostName(vhostName);
				mdTopic.setCreatedTime(new Date());
				mdTopic.setModifiedTime(new Date());
				mdTopic.setStatus("1301");
				mdTopic.setTopicQueueName(ServiceName);
				if(template!=null) {

//					if(template.get("templateId")!=null&&template.get("templateId")!="") {
					if(StringUtils.isNotBlank(template.get("templateId"))) {
						mdTopic.setTemplateId(template.get("templateId"));
					}
				}
//				mdTopic.setQueueName(queueName);
				/*System.out.println(mdTopic.toString());*/
				topicQueueDao.saveService(mdTopic);
				//主题接入信息表
				MdTopicAccess mdTopicAccess = new MdTopicAccess();
				mdTopicAccess.setId(UUIDUtil.getUUId());
				mdTopicAccess.setAccessAppid(origin.get("originId"));
				mdTopicAccess.setTopicQueueNo(topicQueueNo);
				mdTopicAccess.setDelFlag(0);
				mdTopicAccess.setAccessUrl(accessUrl);
				mdTopicAccess.setCreatedTime(new Date());
				mdTopicAccess.setModifiedTime(new Date());
				topicAccessDao.saveService(mdTopicAccess);
				/*System.out.println(mdTopicAccess.toString());*/
				//主题发送信息
				List<MdTopicSend>MdTopicSends=new ArrayList<MdTopicSend>();
				for(int i=0;i<targetList.size();i++) {
					MdTopicSend mdTopicSend =new MdTopicSend();
					Map<String,String>send=targetList.get(i);
					mdTopicSend.setId(UUIDUtil.getUUId());
					mdTopicSend.setSendType(send.get("sendType"));
					mdTopicSend.setTargetAppId(send.get("targetId"));
					mdTopicSend.setTargetUrl(send.get("sendChannel"));
					mdTopicSend.setTopicQueueNo(topicQueueNo);
					mdTopicSend.setDelFlag(0);
					MdTopicSends.add(mdTopicSend);
				}
				/*System.out.println(MdTopicSends.size());
				for(int i=0;i<MdTopicSends.size();i++) {
					System.out.println(MdTopicSends.get(i).toString());
				}*/
				topicSendDao.saveService(MdTopicSends);
				
				
//				rabbitUtil.createQueue(vhostName,queueName);
//				rabbitUtil.createQueue(vhostName,queuesuffix);
		return mdTopic.getId();
	}catch(Exception e) {
		e.printStackTrace();
		return false;
	}
 }
//	@Override
//	//撤回服务接入
//	public int ServiceWidthdraw(String topicQueueNo, String id, int status) {
//		//更新数据库
//		int update = releaseOrRecall(id, status);
//		rabbitPublish.update(topicQueueNo);
//		return update;
//	} 
//	@Override
//	//发布服务接入
//	public int ServiceRelease(String topicQueueNo, String id, int status) {
//		//源应用(根据消息队列编码查询)
//		System.out.println("服务发布topicQueueNo="+topicQueueNo);
//		try{
//			List<MdApp> oriApps = topicQueueDao.queryOriAppBySign(topicQueueNo);
//			MdApp oriApp = null;
//			//1.校验能否发布
//			if(oriApps.size() > 0) {
//				oriApp = oriApps.get(0);
//				System.out.println("服务发布oriApp="+oriApp);
//				System.out.println("服务发布Status="+oriApp.getStatus());
//				if(oriApp.getStatus().equals("1001")) {//2 提示启用源应用
//					System.out.println("返回2");
//					return 2;
//				}
//			}else if(oriApps.size() == 0) {// 3提示配置源应用
//				//判断源应用的状态，如果没有该应用，提示完善节点
//				System.out.println("返回3");
//					return 3;
//			}
//			List<MdApp> tApps = topicQueueDao.querytApp(topicQueueNo);
//			System.out.println("服务发布tApps长度"+tApps.size());
//			//目标应用用户名
//			List<String> tarList = new ArrayList<>();
//			if(tApps.size() > 0) {
//				for(MdApp tApp : tApps) {
//					//判断应用的启用状态，没启用提示启动(1001停用，1002启用)
//					if(tApp.getStatus().equals("1001")) {//4 提示启用目标应用
//						System.out.println("返回4");
//						return 4;
//					}
//				}
//			}
//			//判断目标应用的状态，如果没有该应用，提示完善目标应用节点
//			 else if(tApps.size() == 0)  {
//				 System.out.println("返回5");
//					return 4;
//			}
//			int update = releaseOrRecall(id, status);
//			rabbitPublish.update(topicQueueNo);
//			System.out.println("返回update");
//			return update;
//			}catch(Exception e) {
//				//异常返回0
//				return 0;
//			}
//	}
	
	//获取源应用信息
	@Override
	public List<List<String>> getSourceAppName() {
		List<List<String>> listTotal=new ArrayList<>();
		List<String> nameList=new ArrayList<>();
		List<String> idList=new ArrayList<>();
		List<String> codeList=new ArrayList<>();
		List<Map<String,Object>> list=topicQueueDao. getSourceAppName();
		if(list!=null) {
			for (Map<String, Object> map : list) {
				String appName=map.get("appname").toString();
				String appTableId=map.get("id").toString();
				String appCode=map.get("appcode").toString();
				nameList.add(appName);
				idList.add(appTableId);
				codeList.add(appCode);
			}
			listTotal.add(idList);
			listTotal.add(nameList);
			listTotal.add(codeList);
		}
		return listTotal;
	}

	@Override
	public List<List<String>> getTargetAppName() {
		List<List<String>> listTotal=new ArrayList<>();
		List<String> nameList=new ArrayList<>();
		List<String> idList=new ArrayList<>();
		List<String> codeList=new ArrayList<>();
		List<Map<String,Object>> list=topicQueueDao.getTargetAppName();
		if(list!=null) {
			for (Map<String, Object> map : list) {
				String appName=map.get("appname").toString();
				String appTableId=map.get("id").toString();
				String appCode=map.get("appcode").toString();
				nameList.add(appName);
				idList.add(appTableId);
				codeList.add(appCode);
			}
			listTotal.add(idList);
			listTotal.add(nameList);
			listTotal.add(codeList);
		}
		return listTotal;
	}
	
	
	@Override
	public Page<Map<String, Object>> queryListAll(MdTopic t) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 新增消息队列接入时校验姓名是否重复
	 */
	@Override
	public boolean checkAppName(String topicQueueName, String id) {
		if(StringUtils.isNotBlank(topicQueueName.trim())) {
			List<MdTopic> mdtopics=topicSendDao.selectBycheckName(topicQueueName.trim());
			if(mdtopics.size()>1) {
				return false;
			}else if (mdtopics.size()==0) {
				return true;
			}else {
				// 如果id一致，则可以通过校验填写该名称
				if(StringUtils.isNotBlank(id)) {
					if(mdtopics.get(0).getId().equals(id)) {
						return true;
					}else {
						return false;
					}
				}else {
					return false;
				}
			}
		}else {
			return false;
		}
	}

	
  } 
